
import java.sql.*;

public class UserDao {

    public User findByUsernameAndPassword(String username, String password){
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.获取数据库连接
        Connection con =null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = new User();
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cake_db",
                    "root", "dddd");
            // 3.构建statement，准备执行sql
            String sql = "select * from tbl_user where username = ?";
            pstm = con.prepareStatement(sql);
            pstm.setString(1, username);
//            pstm.setString(2, password);
            rs = pstm.executeQuery();
            while(rs.next()) {
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRealname(rs.getString("realname"));
                user.setState(rs.getInt("state"));
                user.setFailcount(rs.getInt("failcount"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                // 4.关闭链接
                if(rs != null)
                    rs.close();
                if(pstm != null)
                    pstm.close();
                if(con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    public void updateState(String username, int failCount){
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.获取数据库连接
        Connection con =null;
        PreparedStatement pstm = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cake_db",
                    "root", "dddd");
            System.out.println("连接成功");
            String sql = "update tbl_user set failcount = ? where username = ?";
            pstm = con.prepareStatement(sql);
            pstm.setInt(1, failCount);
            pstm.setString(2, username);
            int res =pstm.executeUpdate();
            if(res>0) {
                System.out.println("更新成功！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(pstm != null)
                    pstm.close();
                if(con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
